<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use EasyWeChat\Foundation\Application;
use EasyWeChat\Message\News;
use App\wx_fance;
use DB;

class WxController extends Controller
{       public $app=null;
        public $fance='';
        public function __construct(){
           
            $this->fance=new wx_fance();
            $options = [
            'debug'  => true,
            'app_id' => 'wx03a0ba6232ede5b9',
            'secret' => 'bebe2729f6abf28fda58fbd51d469f0e',
            'token'  => 'cjx666',
            // 'aes_key' => null, // 可选
            // 'log' => [
            //     'level' => 'debug',
            //     'file'  => '/tmp/easywechat.log', // XXX: 绝对路径！！！！
            // ],
            //...
        ];
        $this->app=new Application($options);
        }
       
    public function index(){
        
        $se =$this->app->server;

        $se->setMessageHandler(function($message){
          //return session('Location_X');
            $ww=$message->MsgType;

            switch ($ww) {
                case 'event':
                    # 事件消息...
                    if ($message->Event=='subscribe') {
                        return $this->guanzhu($message);
                    }elseif($message->Event=='unsubscribe'){
                        return $this->quguan($message);
                    }elseif ($message->Event=='CLICK') {
                        if ($message->EventKey=="二维码") {
                              return $this->geterweima($message);
                          }  
                        return $this->zhoubian($message);
                    }elseif ($message->Event=='LOCATION') {  
                        
                      return $this->weizhi($message);   
                    }
                    break;
                case 'text':
                    # 文字消息...       
                    return $this->huifu($message);
                    break;
                case 'image':
                    # 图片消息...
                    return $this->face($message);
                    break;
                case 'voice':
                    # 语音消息...
                    break;
                case 'video':
                    # 视频消息...
                    break;
                case 'location':
                    $openid=$message->FromUserName;
                    $wei=wx_fance::where('openid',$openid)->first();
                    $wei->locaX=$message->Location_X;
                    $wei->locaY=$message->Location_Y;
                    $wei->save();
                    break;
                case 'link':
                    # 链接消息...
                    break;
                // ... 其它消息
                default:
                    # code...
                    break;
            }

        });
        $response = $se->serve();
        // 将响应输出
        return $response;

    }

    public function guanzhu($message){
        $openid = $message->FromUserName;
        $gg=wx_fance::where('openid',$openid)->first();

        if ($gg) {
           $gg->status=1;
           $gg->save();
           return  $news = new News([
                'title'       => '欢迎您再次回来',
                'description' => '...',
                'url'         => 'blog.cjx666.cn',
                'image'       => "http://cjx666.ittun.com/jj.jpg",
            ]);
       }else{
            $key=$message->EventKey; 
           if ($key) {
            $key=str_replace('qrscene_','',$key);
            $parent=DB::table('wx_fances')->where('openid',$key)->first();
                $this->fance->p1=$parent->fid;
                $this->fance->p2=$parent->p1;
                $this->fance->p3=$parent->p2;
             }
            $this->fance->openid=$openid;
            $nick=$this->getNick($openid);
            $this->fance->nick=$nick;
            $img=$this->erweima($openid);
            $this->fance->img=$img; 
            $this->fance->add_time=time();
            $this->fance->save();
           return  $news = new News([
                'title'       => '欢迎来到逗比联盟',
                'description' => '...',
                'url'         => 'blog.cjx666.cn',
                'image'       => "http://cjx666.ittun.com/jj.jpg",
            ]);
        }
    }
    /**
     * 取消关注
     * @param  [type] $openid [description]
     * @return [type]         [description]
     */
    public function quguan($message){
        $openid=$message->FromUserName;
        $gg=wx_fance::where('openid',$openid)->first();
        $gg->status=0;
        $gg->save();
    }
    public function getNick($openid){
        $userService = $this->app->user;
        $uinfo=$userService->get($openid);
        return $uinfo->nickname;
    }
    public function erweima($openid){
        $qrcode = $this->app->qrcode;
        $result = $qrcode->forever($openid);// 或者 $qrcode->forever("foo");
        $ticket = $result->ticket; // 或者 $result['ticket']
        //$url = $result->url;
        $url = $qrcode->url($ticket);
        $content = file_get_contents($url); // 得到二进制图片内容
        $uu=public_path().'/erweima/'.$openid.'.jpg';
        file_put_contents($uu, $content); // 写入文件
        return str_replace(public_path(),'http://cjx666.ittun.com',$uu) ;
    }
    public function aa(){
        $c=new wx_fance();
        $c->openid='dw';
        $c->save();
    }
    //位置
    public function weizhi($message){
        $openid=$message->FromUserName;
        $wei=wx_fance::where('openid',$openid)->first();
        if ($wei->locaX!=$message->Latitude) {
            $wei->locaX=$message->Latitude;
            $wei->locaY=$message->Longitude;
            $wei->save();
        }

    }

    public function zhoubian($message){
        $wei=wx_fance::where('openid',$message->FromUserName)->first();
        if ($wei->locaX=='') {
            return "请同意定位(请在详情页设置或者发送一次地理位置)";
        }
        $n=$message->EventKey=="酒店"?3:'10';
        $url="http://api.map.baidu.com/telematics/v3/local?location=".$wei->locaY.','.$wei->locaX."&keyWord=".$message->EventKey."&output=json&ak=OEjCUuYFCWKvV19pITGOZzPhca60V36W&number=".$n;
        $arr=json_decode(file_get_contents($url),true);
        $contentStr='';
        foreach ($arr['pointList'] as $v) {
            $contentStr.=$v['name'].'位于'.$v['address'].'距离您:'.$v['distance'].'米;联系热线:'.$v['additionalInformation']['telephone'];
            $x=$message->EventKey=="酒店"?$v['additionalInformation']['link']['0']['name'].":".$v['additionalInformation']['link']['0']['url']:'';
            $contentStr.=$x."\n\n";              
        }
       return $contentStr;
    }
    /**
     * 给用户返回二维码
     */
    public function geterweima($message){
        $er=wx_fance::where('openid',$message->FromUserName)->first();
        return $er->img;
    }

    /**
     * 人脸识别
     */
    public function face($message){
         $url="http://apicn.faceplusplus.com/v2/detection/detect?api_key=ef1002769279de059dbec2e7c16acdc2&api_secret=ggLqR_9eg-SzOdUVse4vQxyeZTwwOjZy&url=".$message->PicUrl."&attribute=glass,pose,gender,age,race,smiling";
        $req=file_get_contents($url);
        $arr=json_decode($req,true);
        if (count($arr['face'])==0) {
                return '前路漫漫,请换个姿势!';
            }

        foreach ($arr as $v) {
            $z= $v['0']['attribute']['gender']['value']=='Male' ? '你长得真帅,你是不是才' : '妳好漂亮啊给妳101分,你看起来才';
            $con= $z.$v['0']['attribute']['age']['value'].'岁';
                return $con;
        }
    }

    /**
     * 回复小机器人
     */
    public function huifu($message){
        $url="http://api.jisuapi.com/iqa/query?appkey=f40384daab834d33&question=".$message->Content;
        $arr=json_decode(file_get_contents($url),true);
        return $arr['result']['content'];
    }
}


        